package org.example.struct.array;

import com.alibaba.fastjson.JSON;

/**
 * @author liyishan
 * @date 2023/7/25 11:41
 * @apiNote
 */

public class Test00122MaxProfit2 {
    public static void main(String[] args) {
        int[] a = new int[]{1,4,0,9};
        int count = test1(a);
        System.out.println("count:"+count+";array:" + JSON.toJSON(a));
    }

    public static int test(int[] prices) {
        int len = prices.length;
        if (len < 2) {
            return 0;
        }
        // 0：持有现金
        // 1：持有股票
        // 状态转移：0 → 1 → 0 → 1 → 0 → 1 → 0
        int[][] dp = new int[len][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1; i < len; i++) {
            // 这两行调换顺序也是可以的
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
        }
        return dp[len - 1][0];
    }


    public static int test1(int[] prices) {
        int len = prices.length;
        if (len < 2) {
            return 0;
        }
        int max1 = 0;
        int max2 = -prices[0];
        int preMax1 = max1;
        int preMax2 = max2;
        for (int i = 1; i < len; i++) {
            max1 = Math.max(preMax1, preMax2 + prices[i]);
            max2 = Math.max(preMax2, preMax1 - prices[i]);
            preMax1 = max1;
            preMax2 = max2;
        }
        return  max1;
    }


    public static int test2(int[] prices) {
        int len = prices.length;
        if (len < 2) {
            return 0;
        }
        int res = 0;
        for (int i = 1; i < len; i++) {
            res += Math.max(prices[i] - prices[i - 1], 0);
        }
        return res;
    }



}
